import { Context, IHelper, Application } from 'egg'
import { userErr } from '../controller/user'

interface SuccessParams {
  resp?: any
  msg?: string
}
interface ErrorParams {
  errType: keyof typeof userErr
  error?: any
}

type EggHelper = IHelper & { ctx: Context; app: Application }

export default {
  /**
   * 规范请求成功返回数据
   */
  success({ resp, msg = '请求成功' }: SuccessParams) {
    const { ctx } = this as EggHelper
    ctx.body = {
      errno: 0,
      data: resp ? resp : null,
      message: msg,
    }
    ctx.status = 200
  },

  /**
   * 规范请求失败返回数据
   */
  error({ errType, error }: ErrorParams) {
    const { ctx } = this as EggHelper
    const { errno, msg } = userErr[errType]
    ctx.body = {
      errno,
      msg,
      ...(error && { error }),
    }
    ctx.status = 200
  },

  /**
   * 生成username jwt token
   */
  jwtUsername(username: string, expiresIn = 60 * 60) {
    const { app } = this as EggHelper
    return app.jwt.sign({ username }, app.config.jwt.secret, { expiresIn })
  },
}
